package com.strongbj.iot.devices.hr.response.handle;

import java.net.InetSocketAddress;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.hr.message.HRMessage;
import com.strongbj.iot.devices.hr.message.MQMessageOfHR;
import com.strongbj.iot.devices.hr.response.entity.HeartPackageEntity;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;

/**
 * 门禁心跳包处理类
 * 
 * @author Pingfan
 *
 */
public class HRHeartPackageHandle implements IMessageHandle<HRMessage, Object> {
	protected static Logger logger = LogManager.getLogger(HRHeartPackageHandle.class.getName());
	protected TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	protected static final String ACTION_CODE = "collect032";
//	private HRMessageFactory hrMessageFactory = new HRMessageFactory(); // 门禁消息工厂,用于生产门禁指令
	
	public HRHeartPackageHandle(String doorDirection) {
		super();
	}
	
	@Override
	public boolean isHandle(HRMessage t) {
		if (t.getCommand() == 0x20) { // 心跳包命令类型为0x20
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, HRMessage t) {
		// 取门禁ip
		InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
		String devIp = insocket.getAddress().getHostAddress();

		// 1.发送心跳到MQ, 资产监听
		// 拼接发送消息
		HeartPackageEntity heartPackage = new HeartPackageEntity();
		heartPackage.setDevIp(devIp);
		heartPackage.setCommand(t.getCommand());
		heartPackage.setHeartTime(t.getData()[0]);
		MQMessageOfHR msg = new MQMessageOfHR();
		msg.setActioncode(ACTION_CODE);
		msg.setAwsPostdata(heartPackage);

		// 发送到MQ
		String json = JSON.toJSONString(msg);
		topicSender.send("hrReader", json);
		logger.info("HR设备发送【心跳包】成功! ip={}, topic=hrReader, 数据={}", devIp, json);

//		// 2.回复硬件已收到心跳包【后续根据业务取消回复】
//		// 拼接回复指令
//		byte[] heartPackageResponse = hrMessageFactory.createHRMessage((byte) 0x20, (byte) 0x00, (byte) 0x00, null);
//		String heartPackageResponseHexStr = ByteUtil.byteArrToHexString(heartPackageResponse, true);
//
//		// 服务器向门禁发送心跳回复
//		ByteBuf bs = Unpooled.copiedBuffer(heartPackageResponse);
//		// 设备收到心跳回复后会立即回复心跳,故此处延迟设备心跳间隔后回复
//		try {
//			Thread.sleep(heartPackage.getHeartTime() * 1000);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
//		ChannelFuture cf = ctx.writeAndFlush(bs);
//
//		// 回调函数监听是否发送成功
//		cf.addListener(new ChannelFutureListener() {
//			@Override
//			public void operationComplete(ChannelFuture future) throws Exception {
//				if (future.isSuccess()) {
//					logger.info("采集向HR设备发送【心跳回复】成功, ip={}, 数据={}", devIp, heartPackageResponseHexStr);
//				} else {
//					logger.error("采集向HR设备发送【心跳回复】失败, ip={}, 数据={}", devIp, heartPackageResponseHexStr);
//				}
//			}
//		});
		return null;
	}
}
